package swing.customComp;

import client.UserSession;
import swing.FrameManager;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class WhiteboardListMouseListener extends MouseAdapter {
    JList whiteboardList;
    JPopupMenu whiteboardMenu;
    JPopupMenu refreshMenu;


    public WhiteboardListMouseListener(JList list, JPopupMenu menu){
        whiteboardList = list;
        whiteboardMenu = menu;

        refreshMenu = new JPopupMenu();
        JMenuItem refreshWhiteboard = new JMenuItem("刷新白板列表");
        refreshWhiteboard.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                FrameManager.mainFrame.updateWhiteboardList();
            }
        });
        refreshMenu.add(refreshWhiteboard);
    }

    @Override
    public void mouseDragged(MouseEvent e){
        if (whiteboardList.locationToIndex(e.getPoint()) == -1)
            whiteboardList.clearSelection();

    }

    @Override
    public void mouseClicked(MouseEvent e) {
        // list.locationToIndex(e.getPoint()) 获取被点击的元素index
        // 左键 1   中 2   右键3
        int index = whiteboardList.locationToIndex(e.getPoint());

        if (index == -1) {
            whiteboardList.clearSelection();
            if (e.getButton() == 3){
                refreshMenu.show(whiteboardList, e.getX(), e.getY());
            }
            return;
        }


        if (!UserSession.isGroupSelectionValid())
            return;

        whiteboardList.setSelectedIndex(index);
        UserSession.setSelectedWhiteboardIndex(index);
        if (e.getButton() == 3){
            whiteboardMenu.show(whiteboardList, e.getX(), e.getY());
        }

        // jList.setSelectedIndex(jList.locationToIndex(e.getPoint()));
    }

}
